<?php

namespace app\api\controller;

use app\model\v2\V2Device;
use app\repository\AliIot;
use think\Request;

class AliDevice
{
    private $aliIot;
    private $request;

    public function __construct(AliIot $aliIot, Request $request)
    {
        $this->aliIot = $aliIot;
        $this->request = $request;
    }

    /**
     * 调用阿里 API 播放收款语音
     *
     * 接收参数：
     * $business_id 商户ID
     * $money 收款金额（单位：分）
     * $pay_type, 1-微信，2-支付宝
     */
    public function play()
    {
        $business_id = $this->request->param('business_id');
        $money = $this->request->param('money');
        $pay_type = $this->request->param('pay_type');

        $model_device = $this->findDeviceByBusinessId($business_id);
        if (!$model_device) {
            return jsonData(0, '此商家ID未绑定设备');
        }

        $pay_text = $pay_type == 1 ? '微信' : '支付宝';
        $money_real = $money / 100;
        // 拼接要播报的语音
        $pub_msg = $pay_text . '收款' . $money_real . '元';

        $res = $this->aliIot->iotPubV2(
            $model_device->DeviceName,
            $model_device->ProductKey,
            $model_device->iotInstanceId,
            $pub_msg
        );
        if ($res['err']) {
            return jsonData(0, $res['msg']);
        }
        return jsonData(1, 'ok');
    }

    /**
     * 通过绑定的商家ID查询到设备信息
     */
    private function findDeviceByBusinessId($business_id)
    {
        return V2Device::where('business_id', $business_id)->order('id', 'desc')->find();
    }
}
